package com.bdzl.auth.service.impl;

import com.bdzl.auth.dao.MeauDao;
import com.bdzl.auth.service.MeauService;
import com.bdzl.auth.service.RoleMeauService;
import com.bdzl.auth.service.RoleService;
import com.bdzl.pub.common.Tree;
import com.bdzl.pub.config.Constant;
import com.bdzl.pub.entity.sys.MeauDO;
import com.bdzl.pub.entity.sys.RoleDO;
import com.bdzl.pub.util.file.BASE64DecodedMultipartFile;
import com.bdzl.pub.util.file.OssUploadFileUtil;
import com.bdzl.pub.util.param.BuildTree;
import com.bdzl.pub.vo.sys.MeauVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

import static java.util.stream.Collectors.toList;


@Service
public class MeauServiceImpl implements MeauService {
	@Autowired
	private MeauDao meauDao;
	@Autowired
	private MeauService meauService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private RoleMeauService roleMeauService;



	@Override
	public MeauDO get(String menuId){
		return meauDao.get(menuId);
	}

	@Override
	public List<MeauDO> list(Map<String, Object> map){
		return meauDao.list(map);
	}

	@Override
	public List<MeauVO> voList(Map<String, Object> map){
		return meauDao.voList(map);
	}

	@Override
	public int count(Map<String, Object> map){
		return meauDao.count(map);
	}

	@Override
	public int save(MeauDO meau){
		return meauDao.save(meau);
	}

	@Override
	public int update(MeauDO meau){		//如果头像不为空 不以http开头
		if (meau.getMeauIcon()!=null && !meau.getMeauIcon().equals("") && !meau.getMeauIcon().startsWith("http")){
			try {
				//上传百度云
				MultipartFile file1 = BASE64DecodedMultipartFile.base64ToMultipart(meau.getMeauIcon());
				String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(file1, "loan/config ");
				//修改头像
				meau.setMeauIcon(docUrl);
				//获取旧头像
				String userHeadImg = meauDao.get(meau.getMeauIcon()).getMeauIcon();
				if (userHeadImg!=null && userHeadImg.startsWith("http")){
					OssUploadFileUtil.remove(userHeadImg);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return meauDao.update(meau);
	}

	@Override
	public int remove(String menuId){
		return meauDao.remove(menuId);
	}

	@Override
	public int batchRemove(String[] menuIds){
		return meauDao.batchRemove(menuIds);
	}

	@Override
	public Set<String> listUserPerms(Integer id) {
		List<String> perms = meauDao.listUserPerms(id);
		Set<String> permsSet = new HashSet<>();
		for (String perm : perms) {
			if (StringUtils.isNotBlank(perm)) {
				permsSet.addAll(Arrays.asList(perm.trim().split(",")));
			}
		}
		return permsSet;
	}

	@Override
	public String getPermsByUrl(String url) {
		return meauDao.getPermsByUrl(url);
	}

	@Override
	public List<MeauDO> getMenuByPid(List<String> pId) {
		return meauDao.getMenuByPid(pId);
	}

	/**
	 * 添加菜单
	 * @param meau 菜单信息
	 * @return 1成功，0失败，-1重复，-2菜单ID不合法
	 */
	@Override
	public int add(MeauDO meau){
		int r=0;
		try{
			String menuId=meau.getMenuId();
			String parentId=meau.getMenuPid();
			if (parentId==null||parentId==Constant.DEPT_ROOT_ID||parentId.equals(Constant.DEPT_ROOT_ID)){
				meau.setMenuPid(Constant.DEPT_ROOT_ID);
			}else {
				//判断menuId是否符合添加规则（必须以 父ID + “_” 开头）
				boolean b = menuId.startsWith(parentId+"_");
				if (!b){
					return -2;
				}
			}
			if (meau.getMeauOrder()==null){
				meau.setMeauOrder(0);
			}
			//添加
			MeauDO tmp = meauDao.get(menuId);
			if (tmp!=null){
				return -1;
			}
			//如果头像不为空 不以http开头
			if (meau.getMeauIcon()!=null &&  !meau.getMeauIcon().equals("")  && !meau.getMeauIcon().startsWith("http")){
				try {
					//上传百度云
					MultipartFile file1 = BASE64DecodedMultipartFile.base64ToMultipart(meau.getMeauIcon());
					String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(file1, "loan/config ");
					//修改头像
					meau.setMeauIcon(docUrl);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			r=meauDao.save(meau);
			return r;
		}catch (Exception e){
			e.printStackTrace();
			return -3;
		}
	}

	@Override
	public boolean verify(String id) {
		return meauDao.verify(id);
	}

	@Override
	public int removeByPid(String pId) {
		return meauDao.removeByPid(pId);
	}

	/**
	 * 根据角色信息加载pc权限菜单
	 * @param roleIds 当前登录者拥有的全部角色
	 * @param treeType 加载树的类型，admin：pc端，app 代表移动端
	 * @param selectRoleId 被选中的角色，null代表无选中角色
	 * @param orgId 机构id
	 * @return Tree<MenuDO> 权限菜单树
	 */
	@Override
	public Map<String, Object> getTree(Integer[] roleIds, String treeType, String selectRoleId, Integer orgId) {
		Map<String,Object> map1 = new HashMap<>();
		//系统版本拥有的菜单
		List<MeauDO> menuLimitList = new ArrayList<>();
		//系统角色拥有的权限菜单
		List<MeauDO> menus = new ArrayList<>();
		try {
			map1.put("meauClassify",treeType);
			//如果是PC端获取权限
			menuLimitList = meauService.list(map1);
			if (Arrays.asList(roleIds).contains(1)) {
				//超管加载全部
				menus = menuLimitList;
			}else {
				if ("PC".equals(treeType)) {
					menus = meauDao.listMenuAndBtnByRoleIds(roleIds);
				}else if ("APP".equals(treeType)) {
					menus= meauDao.listAppMenuAndBtnByRoleIds(roleIds);
				}
			}
			//取交集
			List<MeauDO> finalMenuLimitList = menuLimitList;
			menus = menus.stream().filter(item -> finalMenuLimitList.contains(item)).collect(toList());
			// 根据选中的roleId查询权限，并构建勾选树
			List<String> menuIds=null;
			if (selectRoleId!=null){
				menuIds = roleMeauService.listMenuIdByRoleId(selectRoleId,treeType);
				List<String> list=menus.stream().map(MeauDO::getMenuPid).distinct().collect(toList());
				menuIds.removeIf(item->list.contains(item));
			}
			Tree<MeauDO> t = buidTreeAndSelected(menus, menuIds);
			Map<String,Object> param = new HashMap<>();
			param.put("tree",t);
			param.put("userMenuIds",menuIds);
			return param;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @param menus 构建树的权限菜单
	 * @param selectedMenuIds 选中的菜单ID
	 * @return Tree<MenuDO> 权限菜单树
	 */
	@Override
	public Tree<MeauDO> buidTreeAndSelected(List<MeauDO> menus,List<String> selectedMenuIds){
		List<Tree<MeauDO>> trees = new ArrayList<>();
		try{
			for (MeauDO sysMenuDO :  menus) {
				Tree<MeauDO> tree = new Tree<>();
				tree.setId(sysMenuDO.getMenuId());
				tree.setParentId(sysMenuDO.getMenuPid());
				tree.setText(sysMenuDO.getMeauName());
				tree.setType(sysMenuDO.getMeauType());
				Map<String, Object> state = new HashMap<>();
				if (selectedMenuIds!=null&& selectedMenuIds.size()>0){
					if (selectedMenuIds.contains(sysMenuDO.getMenuId())) {
						tree.setSelected(true);
						state.put("selected", true);
					} else {
						state.put("selected", false);
						tree.setSelected(false);
					}
				}
				tree.setState(state);
				trees.add(tree);
			}
			// 默认顶级菜单为０，根据数据库实际情况调整
			Tree<MeauDO> t = BuildTree.build(trees);
			return t;
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
